from django.shortcuts import render
from Doctor_django.utils.alipaysdk import AliPaySDK
from rest_framework.response import Response
from rest_framework.viewsets import ViewSet
from rest_framework.decorators import action
from rest_framework import status
from orders.models import OrdersModel
from orders.models import CouponLogModel


# 视图集   Viewset   ModelViewset
class AliPayViewSet(ViewSet):

    @action(methods=['GET'], detail=False)
    def link(self, request):
        # 获取订单支付链接
        order_id = request.query_params.get('order_id')
        # 根据订单id，查询订单信息
        try:
            order = OrdersModel.objects.get(id=order_id)
            if order.order_status > 0:
                return Response({'message', '订单不能重复支付或者订单已经超时'}, status=status.HTTP_204_NO_CONTENT)

        except OrdersModel.DoesNotExist:
            print('订单不存在，响应异常信息....')
            return Response({'message', '订单不存在，请重新下单！'}, status=status.HTTP_204_NO_CONTENT)

        alipay = AliPaySDK()
        link = alipay.page_pay(order.order_number, order.real_price, order.name)
        print('-----------查看支付宝返回结果--------------')
        print(link)
        print('--------------支付宝返回结束---------------')
        return Response(link)

    @action(methods=['GET'], detail=False)
    def return_result(self, request):
        # 所有查询参数，转换成字典格式数据
        data = request.query_params.dict()
        # 校验数据，验签
        alip = AliPaySDK()
        success = alip.check_sign(data)
        if not success:
            return Response({'message': '支付宝同步通知结果不存在或者异常'}, status=status.HTTP_201_CREATED)

        # 从支付宝同步通知结果中，获取订单号
        order_number = data.get('out_trade_no')
        # 根据订单号，查询订单，并修改订单状态

        try:
            order = OrdersModel.objects.get(order_number=order_number)
            if order.order_status > 1:
                return Response({'message', '订单超时或者已经取消...'}, status=status.HTTP_204_NO_CONTENT)
        except OrdersModel.DoesNotExist:
            return Response({'message', '订单不存在....'}, status=status.HTTP_204_NO_CONTENT)

        # 表示成功
        # 将当前支付成功的信息，和订单查询，返回给前端
        # 修改状态：订单状态     优惠劵状态：使用时间
        # 判断当前订单状态是否为0
        if order.order_status == 0:
            # 根据订单号，查询支付结果
            # 后端异步通知无法接收   查询替代异步通知
            result = alip.query(order_number)
            # 支付结果，以后端为准
            print('打印订单查询返回结果....')
            print(result)
            print('-----')
            if result.get('trade_status', None) in ['TRADE_SUCCESS', 'TRADE_FINISHED']:
                # 表示用后支付成功，修改订单状态
                order.pay_time = result.get('send_pay_date')
                order.order_status = 1
                order.save()

                # 修改优惠劵状态
                coupon_log = CouponLogModel.objects.filter(order=order).first()
                if coupon_log:
                    coupon_log.use_time = order.pay_time
                    coupon_log.use_status = 1
                    coupon_log.save()

            # 将数据查询并返回给前端展示
            return Response({
                'pay_time': order.pay_time,
                'real_price': order.real_price
            })
